//
//  CollectionDB.m
//  FlowerRainGround
//
//  Created by 阿仁欧巴 on 16/4/21.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "CollectionDB.h"
#import "DBManger.h"

@implementation CollectionDB

//初始化
- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataBase = [DBManger shareInstanceDbName:kCollectSqlite].dateBase;
    }
    return self;
}


//创建收藏的数据表

- (void)createTable
{
    FMResultSet *set = [self.dataBase executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'", kCollectSqlite]];
//查询错误的一步
    [set next];
//判断数据表是否已经存在
    NSInteger count = [set intForColumnIndex:0];
    if (count) {
        NSLog(@"数据库已经存在");
    } else {
    //创建新的数据表
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE %@ (CollectID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL, userID text, title text, smallIcon text, ID text)", kCollectSqlite];
    //执行数据库语句
        BOOL result = [_dataBase executeQuery:sql];
        if (result) {
            NSLog(@"创建数据库成功");
        } else {
            NSLog(@"创建数据库失败");
        }
    }
    
}

//插入一条数据

- (void)insertModel:(FirstModel *)model
{
    NSMutableString * query = [NSMutableString stringWithFormat:@"INSERT INTO %@ (userID,title,ID,smallIcon) values (?,?,?,?)", kCollectSqlite];
    //创建插入内容
    NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:0];
    //如果用户存在  就插入用户id
    if (![[userManager getUsrID] isEqualToString:@" "]) {
        [arguments addObject:[userManager getUsrID]];
    }
    if (model.title) {
        [arguments addObject:model.title];
    }
    if (model.ID) {
        [arguments addObject:model.ID];
    }
    if (model.smallIcon) {
        [arguments addObject:model.smallIcon];
    }
    NSLog(@"收藏了一条数据");
    //执行数据库语句 插入一条记录
    [_dataBase executeUpdate:query withArgumentsInArray:arguments];
    
}

//删除一条数据

- (void)deleteModelWithTitle:(NSString *)title
{
    NSString * query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE title = '%@'", kCollectSqlite, title];
    NSLog(@"删除成功");
    [_dataBase executeUpdate:query];

}

//查询所有数据 获得所有数据 然后 再显示到收藏的列表中

- (NSArray *)findModelWithUserID:(NSString *)userID
{
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userID = '%@'", kCollectSqlite, userID];
    //执行
    FMResultSet *set = [_dataBase executeQuery:query];
    NSLog(@"rs 是：%@",set);
//创建一个存放查询数据的数组 大小
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[set columnCount]];
    while ([set next]) {
        FirstModel *model = [[FirstModel alloc] init];
        model.ID = [set stringForColumn:@"ID"];
        model.title = [set stringForColumn:@"title"];
        model.smallIcon = [set stringForColumn:@"smallIcon"];
        [array addObject:model];
    }
    NSLog(@"array = %@", array);
    [set close];
    return array;
    
}




















@end
